package com.hu.bgp.client.presenter;

import java.util.HashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.hu.bgp.client.EventBus;
import com.hu.bgp.client.localevent.PlaceChangedEvent;
import com.hu.bgp.client.localevent.RequestPlaceChange;
import com.hu.bgp.client.rpc.BgpService;
import com.hu.bgp.client.rpc.BgpServiceAsync;
import com.hu.bgp.client.widgets.uicomponents.GameTypeTableUser;
import com.hu.bgp.framework.clientapi.util.Firebug;
import com.hu.bgp.shared.data.ClientGameType;
import com.hu.bgp.shared.data.ClientGameTypeCollection;

public class GameTypes implements Presenter
{
	public interface Display
	{
		HasClickHandlers getSelectButton();

		GameTypeTableUser getGameTypetable();

		Widget asWidget();
	}

	private Display view;
	private BgpServiceAsync bgpService;
	private EventBus eventBus;

	@Inject
	public GameTypes(Display view, BgpServiceAsync bgpService, EventBus eventBus) {
		this.view = view;
		this.bgpService = bgpService;
		this.eventBus = eventBus;
		bind();
	}

	private void init()
	{
		bgpService
				.getClientGameTypeCollection(new AsyncCallback<ClientGameTypeCollection>() {
					public void onSuccess(ClientGameTypeCollection result)
					{
						for (ClientGameType gameType : result) {
							view.getGameTypetable().addGameRow(gameType);
						}
					}

					public void onFailure(Throwable caught)
					{
						Window.alert("failed to get Game types");

					}
				});
	}

	private void bind()
	{
		view.getSelectButton().addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event)
			{
				GameSessionPlace gp = new GameSessionPlace();
				gp.setGameAlias(view.getGameTypetable().getSelection()
						.getAlias());
				eventBus.fireEvent(new RequestPlaceChange(gp));
			}

		});
	}

	public void go(final HasWidgets container)
	{
		container.clear();
		init();
		container.add(view.asWidget());
	}

}
